<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>SQL填充工具</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 引入MySQL版本的node-sql-parser -->
    <script src="https://unpkg.com/node-sql-parser/umd/mysql.umd.js"></script>
    <!-- 替换为更稳定的sql-formatter CDN链接 -->
    <script src="https://unpkg.com/sql-formatter@latest/dist/sql-formatter.min.js"></script>
    <style>
        /* 限制JSON容器最大高度 */
        .json-container {
            max-height: 300px;
            overflow-y: auto;
        }
        /* 调整图标按钮大小 */
        .icon-btn {
            padding: 0.375rem 0.75rem; /* 比原按钮更小 */
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <!-- 添加浮动提示容器 -->
    <div id="copyNotice" class="fixed top-4 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg opacity-0 transition-opacity duration-300"></div>

    <div class="container max-w-6xl mx-auto px-4 py-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-6">SQL参数填充工具</h1>
        
        <div class="input-group mb-6">
            <label for="sqlInput" class="block text-sm font-medium text-gray-700 mb-2">原始SQL（使用?作为参数占位符）：</label>
            <textarea id="sqlInput" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500" placeholder="示例：SELECT ? FROM users WHERE age > ?"></textarea>
        </div>

        <div class="input-group mb-6">
            <label for="paramsInput" class="block text-sm font-medium text-gray-700 mb-2">参数列表（格式：值 或 值(类型)，类型可选，默认Long）：</label>
            <input type="text" id="paramsInput" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500" placeholder="示例：'张三'(String), 18 或 6">
        </div>

        <button onclick="handleBuild()" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors">构建可执行SQL</button>

        <div class="result-group mt-8">
            <div class="mb-6">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="text-xl font-semibold text-gray-800">填充后的SQL：</h3>
                    <div class="flex gap-2">
                        <!-- 复制按钮（图标版） -->
                        <button onclick="copyText('filledSQL')" class="bg-blue-500 text-white icon-btn rounded-lg hover:bg-blue-600 transition-colors shadow-sm">
                            <i class="fas fa-copy"></i> <!-- 复制图标 -->
                        </button>
                        <!-- 新增格式化按钮 -->
                        <button onclick="formatSQL()" class="bg-teal-500 text-white icon-btn rounded-lg hover:bg-teal-600 transition-colors shadow-sm">
                            <i class="fas fa-code"></i> 格式化
                        </button>
                    </div>
                </div>
                <pre id="filledSQL" class="bg-gray-50 p-4 rounded-lg overflow-x-auto"></pre>
            </div>
        
            <div>
                <div class="flex items-center justify-between mb-3">
                    <h3 class="text-xl font-semibold text-gray-800">简化版JSON：</h3>
                    <div class="flex gap-2">
                        <!-- 复制按钮（图标版） -->
                        <button onclick="copyText('simplifiedJSON')" class="bg-blue-500 text-white icon-btn rounded-lg hover:bg-blue-600 transition-colors shadow-sm">
                            <i class="fas fa-copy"></i> <!-- 复制图标 -->
                        </button>
                        <!-- 可视化按钮（图标版） -->
                        <button onclick="copyAndOpenJsonEditor()" class="bg-purple-500 text-white icon-btn rounded-lg hover:bg-purple-600 transition-colors shadow-sm">
                            <i class="fas fa-eye"></i> <!-- 可视化图标 -->
                        </button>
                    </div>
                </div>
                <pre id="simplifiedJSON" class="bg-gray-50 p-4 rounded-lg json-container overflow-x-auto"></pre>
            </div>
        </div>
</div>

    <script>
                // 显示浮动提示（替代alert）
        function showCopyNotice(text) {
            const notice = document.getElementById('copyNotice');
            notice.textContent = text;
            notice.style.opacity = '1';
            setTimeout(() => notice.style.opacity = '0', 2000);
        }

        // 复制文本（修改为使用浮动提示）
        function copyText(elementId) {
            const text = document.getElementById(elementId).textContent;
            navigator.clipboard.writeText(text)
                .then(() => showCopyNotice('已复制到剪贴板！'))
                .catch(() => showCopyNotice('复制失败，请手动选中内容'));
        }

        // 复制JSON并跳转可视化编辑器
        function copyAndOpenJsonEditor() {
            // 先复制JSON
            copyText('simplifiedJSON');
            // 跳转编辑器（使用用户指定链接）
            window.open('https://json.0xfab1.net/editor', '_blank');
        }
        // 简化JSON：过滤null/空数组/空对象
        function simplifyAst(ast) {
            if (typeof ast !== 'object' || ast === null) return ast;
            
            // 处理数组
            if (Array.isArray(ast)) {
                const filtered = ast.map(item => simplifyAst(item)).filter(item => 
                    item !== null && (typeof item !== 'object' || Object.keys(item).length > 0)
                );
                return filtered.length > 0 ? filtered : undefined;
            }

            // 处理对象
            const simplified = {};
            for (const [key, value] of Object.entries(ast)) {
                const simplifiedValue = simplifyAst(value);
                if (simplifiedValue !== null && simplifiedValue !== undefined) {
                    simplified[key] = simplifiedValue;
                }
            }
            return Object.keys(simplified).length > 0 ? simplified : undefined;
        }

        // 移除重复的copyText函数（原使用alert的版本）
        // 以下为原重复代码，需删除：
        // function copyText(elementId) {
        //     const text = document.getElementById(elementId).textContent;
        //     navigator.clipboard.writeText(text)
        //         .then(() => alert('已复制到剪贴板！'))
        //         .catch(() => alert('复制失败，请手动选中内容'));
        // }

            // 新增：存储原始未格式化的SQL
            let rawFilledSQL = '';
        
            function handleBuild() {
                const rawSQL = document.getElementById('sqlInput').value.trim();
                const paramsStr = document.getElementById('paramsInput').value.trim();
        
                if (!rawSQL || !paramsStr) {
                    alert('请填写完整的SQL和参数列表');
                    return;
                }
        
                const paramList = [];
                const paramRegex = /([^,]+?)(?:\((\w+)\))?(?=,|$)/g;
                let match;
                while ((match = paramRegex.exec(paramsStr)) !== null) {
                    const value = match[1].trim();
                    const type = match[2] || 'Long';
                    paramList.push({ value, type });
                }
        
                const placeholderCount = (rawSQL.match(/\?/g) || []).length;
                if (paramList.length !== placeholderCount) {
                    alert(`参数数量（${paramList.length}个）与?占位符数量（${placeholderCount}个）不匹配`);
                    return;
                }
        
                // 生成原始未格式化的SQL
                rawFilledSQL = rawSQL;
                paramList.forEach((param) => {
                    const formattedValue = param.type === 'String' 
                        ? `'${param.value}'` 
                        : param.value;
                    rawFilledSQL = rawFilledSQL.replace('?', formattedValue);
                });
        
                // 默认显示未格式化的SQL
                document.getElementById('filledSQL').textContent = rawFilledSQL;
        
                // 生成简化版JSON（逻辑不变）
                try {
                    const parser = new NodeSQLParser.Parser();
                    const ast = parser.astify(rawFilledSQL);
                    const simplified = simplifyAst(ast);
                    document.getElementById('simplifiedJSON').textContent = 
                        JSON.stringify(simplified, null, 2);
                } catch (error) {
                    document.getElementById('simplifiedJSON').textContent = 
                        `解析失败：${error.message}\n（请检查SQL语法是否正确）`;
                }
            }
        
            // 新增：格式化SQL按钮点击事件
            function formatSQL() {
                if (!rawFilledSQL) return;
                const formattedSQL = sqlFormatter.format(rawFilledSQL);
                document.getElementById('filledSQL').textContent = formattedSQL;
            }
    </script>
</body>
</html>